/*
 * @Author: zqx me_zqx@163.com
 * @Date: 2025-06-26 17:36:19
 * @LastEditors: zqx me_zqx@163.com
 * @LastEditTime: 2025-06-26 17:50:33
 * @FilePath: /XMate-h5/src/store/modules/study/study.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from "pinia";
import {
  getUserkngAPI,
  generateCourseAPI,
  updateCourseStudyStatusAPI
} from "@/services/study";
import type { StudyArchive, Chapter, Knowledge } from "@/types/study";

export const useMinutesStore = defineStore("studyStore", {
  state: () => ({
    courseData: null as StudyArchive | null,
    conferenceId: ""
  }),
  getters: {
    courseFlatList(state): Knowledge[] {
      if (!state.courseData) return [];
      const flatList: Knowledge[] = [];
      state.courseData.chapterList?.forEach((item: Chapter) => {
        if (item.kngList) {
          item.kngList.forEach((kng: Knowledge) => {
            flatList.push(kng);
          });
        }
      });
      return flatList;
    },
    completeProgress(): number {
      const flatList = this.courseFlatList;
      if (flatList.length === 0) {
        return 0;
      }
      // 计算状态为 2 的数量
      const completedCount = flatList.filter(
        (item: Knowledge) => item.status === 2
      ).length;
      // 计算进度
      const totalCount = flatList.length;
      const progress = totalCount > 0 ? ((completedCount / totalCount) * 100).toFixed(0) : 0;
      return Number(progress);
    }
  },
  actions: {
    // 获取学习包
    async getUserkngAction(conferenceId: string) {
      if (conferenceId) {
        this.conferenceId = conferenceId;
      }
      const res = await getUserkngAPI(conferenceId);
      this.courseData = res.data;
      return res;
    },
    // 生成学习课程
    async generateUserKngAction(confId: string) {
      const res = await generateCourseAPI(confId);
      return res;
    },
    // 更新课件学习状态
    async updateCourseStudyStatusAction(
      packageId: string,
      kngId: string,
      status: string
    ) {
      const res = await updateCourseStudyStatusAPI(packageId, kngId, status);
      await this.getUserkngAction(this.conferenceId);
      return res;
    }
  }
});
